package cn.itrip.auth.service.impl;

import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.common.MD5;
import cn.itrip.common.RedisAPI;
import com.alibaba.fastjson.JSON;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {
    @Resource
    private RedisAPI redisAPI;

    /**
     * 生产token字符串
     * 前端PC-usercode-userid-creationdate-rendom[6位]
     *
     * @param userAgent
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String generateToken(String userAgent, ItripUser user) throws Exception {
        StringBuilder str = new StringBuilder();
        str.append("token:");
        UserAgent agent = UserAgent.parseUserAgentString(userAgent);
        if (agent.getOperatingSystem().isMobileDevice()) {
            str.append("MOBILE-");
        } else {
            str.append("PC-");
        }
        str.append(MD5.getMd5(user.getUserCode(), 32) + "-");
        str.append(user.getId().toString() + "-");
        str.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "-");
        str.append(MD5.getMd5(userAgent, 6));
        return str.toString();
    }

    @Override
    public void save(String token, ItripUser user) throws Exception {
        if (token.startsWith("token:PC-")) {
            redisAPI.set(token, 2 * 60 * 60, JSON.toJSONString(user));
        } else {
            redisAPI.set(token, JSON.toJSONString(user));
        }
    }

    @Override
    public boolean validateToken(String userAgent, String token) throws Exception {
        if (!redisAPI.exists(token)) {
            return false;
        } else {
            String agentMD5 = token.split("-")[4];
            if (!MD5.getMd5(userAgent, 6).equals(agentMD5)) {
                return false;
            }
            return true;
        }
    }

    @Override
    public void remove(String token) throws Exception {
        redisAPI.del(token);
    }

    private int protectedTime = 30 * 60;
    private int delay = 2 * 60;

    @Override
    public String reloadToken(String userAgent, String token) throws Exception {
        //1.验证token是否有效
        if (!redisAPI.exists(token)) {
            throw new Exception("token无效");
        }
        //2.能不能置换--(riseTime生成时间 nowTime当前时间）
        Date riseTime = new SimpleDateFormat("yyyyMMddHHmmss").parse(token.split("-")[3]);
        long nowTime = Calendar.getInstance().getTimeInMillis() - riseTime.getTime();
        if (nowTime < protectedTime) {
            throw new Exception("token置换保护时间，不能置换，剩余" + (protectedTime - nowTime) / 1000);
        }
        //3.进行置换
        String user = redisAPI.get(token);
        ItripUser itripUser = JSON.parseObject(user, ItripUser.class);
        String newToken = this.generateToken(userAgent,itripUser);
        //4.旧的token延时过程
        redisAPI.set(token,delay,user);
        //5.新的token保存至redis
        this.save(newToken,itripUser);
        return newToken;
    }
}
